<?php


namespace app\badmin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Redis;
use oss\Oss;

class HouseTableConfig extends BaseModel {

    const TYPE = [
        ['key' => 1, 'val' => '详版'],
        ['key' => 2, 'val' => '定制版'],
        ['key' => 3, 'val' => '别墅—跃层版'],
    ];

    const TYPES = [
        1 => '详版',
        2 => '定制版',
        3 => '别墅—跃层版',
    ];

    /**
     * 添加
     * @param $params
     * @return bool
     */
    public static function add($params) {
        $redisModel = Redis::getInstance();
        $request = $redisModel->hget("houseTable_Preview_request_{$params['company_id']}", $params['key']);
        if (!$request) {
            Err::add("请返回重新尝试", RespCode::PARAMS_ERR);
            return false;
        }
        $request = json_decode($request, true);

        $count = self::where("city_code", $request['city_code'])
            ->where('company_id', $request['company_id'])
            ->whereTime('itime', 'today')
            ->count();
        if ($count > 30) {
            Err::add("发布失败！{$request['city_name']}房源表当日发布次数已达上限（30次）", RespCode::PARAMS_ERR);
            return false;
        }
        //第一次提交
        if (db("house_table_config")
            ->where('city_code', $request['city_code'])
            ->where('company_id', $request['company_id'])
            ->where('type', $request['type'])
            ->select()) {
            Err::add("同一个城市只能添加一种表格类型", RespCode::PARAMS_ERR);
            return false;
        }
        if ($params['level'] == 1) {
            Err::add("是否继续发布", RespCode::SUCCESS);
            return false;
        } else {//第二次提交
            if (empty($params['img'])) {
                Err::add("img不能为空", RespCode::PARAMS_ERR);
                return false;
            }
            $data = [
                'company_id' => $request['company_id'],
                'city_code'  => $request['city_code'],
                'city_name'  => $request['city_name'],
                'type'       => $request['type'],
                'area_name'  => empty($request['area_name']) ? "" : $request['area_name'],
                'area_code'  => empty($request['area_code']) ? "" : $request['area_code'],
                'download'   => $params['img'],
                'itime'      => time(),
            ];
            self::insert($data);
            $redisModel->del("houseTable_Preview_resp_{$params['company_id']}");
            $redisModel->del("houseTable_Preview_request_{$params['company_id']}");
            return true;
        }
    }

    /**
     * 列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($params) {
        empty($params['page']) ? $page = 1 : $page = $params['page'];
        empty($params['long']) ? $long = 10 : $long = $params['long'];
        $column = ['city_name', 'type', 'area_name', 'itime', 'id', 'download'];
        $order = ['id' => 'desc'];
        $map[] = ['company_id', '=', $params['company_id']];
        //城市
        if (!empty($params['city_code1'])) {
            $map[] = ['city_code', '=', $params['city_code1']];
        }
        //类型
        if (!empty($params['type'])) {
            $map[] = ['type', '=', $params['type']];
        }
        $data = self::list_query($map, $page, $long, $column, $order);
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['itime'] = date('Y-m-d H:i:s', $v['itime']);
            $data['data'][$k]['type'] = self::TYPES[$v['type']];
        }
        return $data;
    }

    /**
     * 列表sql
     * @param $map
     * @param $page
     * @param $long
     * @param $column
     * @param $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function list_query($map, $page, $long, $column, $order) {
        $count = db("house_table_config")
            ->where($map)
            ->count();
        if ($count == 0) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
            return $result;
        } else {
            $data = db("house_table_config")
                ->where($map)
                ->page($page, $long)
                ->field($column)
                ->order($order)
                ->select();
            $pageNum = ceil($count / $long);
            $result = [
                'page'    => $page,
                'pageNum' => $pageNum,
                'count'   => $count,
                'data'    => $data,
            ];
            return $result;
        }
    }

    /**
     * 点击上传预览
     */
    public static function clickPreview($params) {
        $company_codes = db('company')->where('id',$params['company_id'])->value('city_code');
        $company_codes = explode(',', $company_codes);
        $arr = [];
        foreach ($company_codes as $company_code) $arr[] = explode('-', $company_code)[0];
        if (!in_array($params['city_code'], $arr)) {
            Err::add("选择的城市不存在，请刷新后尝试", RespCode::PARAMS_ERR);
            return false;
        }

        if ($params['account_type'] != 0) {
            Err::add('当前账号不是公司账号', RespCode::PARAMS_ERR);
            return false;
        }
        //详版或者定制版
        if ($params['type'] == 1 || $params['type'] == 2) {
            if (empty($params['area_name']) || empty($params['area_code'])) {
                Err::add('请选择区域', RespCode::PARAMS_ERR);
                return false;
            }
        }
        //定制版
        if ($params['type'] == 2) {
            if (count(explode(',', $params['area_name'])) > 1 || count(explode(',', $params['area_code'])) > 1) {
                Err::add('定制版只能选择一个区域', RespCode::PARAMS_ERR);
                return false;
            }
        }
        //定制、详版
        if ($params['type'] == 1 || $params['type'] == 2) {
            $result = House::houseByArea($params);
            $_type = 1;
        } else {
            //别墅版
            $result = House::houseByCity($params);
            $_type = 3;
        }
        if (!$result) {
            Err::add("未找到房源数据", RespCode::PARAMS_ERR);
            return false;
        }
        $time = time();
        $redisModel = Redis::getInstance();
        $redisModel->hset("houseTable_Preview_resp_{$params['company_id']}", $time, json_encode(['type' => $_type, 'list' => $result]));//房源数据
        $redisModel->hset("houseTable_Preview_request_{$params['company_id']}", $time, json_encode($params));//请求数据
        return $time;
    }

    /**
     * 获取结果缓存key
     * @param $params
     * @return mixed
     */
    public static function getRespCacheKey($params) {
        $redisModel = Redis::getInstance();
        $data = $redisModel->hget("houseTable_Preview_resp_{$params['company_id']}", $params['key']);
        return json_decode($data, true);
    }

    /**
     * 获取请求缓存key
     * @param $params
     * @return mixed
     */
    public static function getRequestCacheKey($params) {
        $redisModel = Redis::getInstance();
        $data = $redisModel->hget("houseTable_Preview_request_{$params['company_id']}", $params['key']);
        return json_decode($data, true);
    }

    /**
     * 删除
     * @param $params
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function del($params) {
        $data = self::where('id', $params['id'])->find();
        if (empty($data)) {
            Err::add("数据不存在", RespCode::PARAMS_ERR);
            return false;
        }
        if (!empty($data['download'])) {
            $oss = Oss::getInstance();
            $oss->delOneFile($data['download']);
        }
        self::where('id', $params['id'])->delete();
        return true;
    }

}